/**
 * 后台管理模块入口
 * 集成所有管理员相关的路由和功能
 */

const express = require('express');
const logger = require('../logger');
const adminAuthMiddleware = require('./middleware/adminAuth.middleware');
const { performanceMonitor, trafficMonitor, resourceMonitor, userActivityMonitor } = require('./middleware/monitoring.middleware');

// 导入路由
const authRoutes = require('./routes/auth.routes');
const userRoutes = require('./routes/user.routes');
const contentRoutes = require('./routes/content.routes');
const versionRoutes = require('./routes/version.routes');
const dashboardRoutes = require('./routes/dashboard.routes');
const statsRoutes = require('./routes/stats.routes');
const adminUserRoutes = require('./routes/adminUser.routes');

const router = express.Router();

/**
 * @function initializeAdminModule
 * @description 初始化后台管理模块
 * @returns {Object} 配置好的路由对象
 */
function initializeAdminModule() {
    logger.info('初始化后台管理模块');
    
    // 应用监控中间件
    router.use(performanceMonitor);
    router.use(trafficMonitor);
    router.use(resourceMonitor);
    router.use(userActivityMonitor);

    // 后台管理根路径
    router.get('/', (req, res) => {
        logger.info('访问后台管理首页');
        res.status(200).json({
            message: '欢迎访问灵犀指引后台管理系统',
            version: '1.0.0',
            timestamp: new Date().toISOString()
        });
    });

    // 健康检查端点
    router.get('/health', (req, res) => {
        logger.info('后台管理模块健康检查');
        res.status(200).json({
            status: 'ok',
            timestamp: new Date().toISOString(),
            module: 'admin'
        });
    });

    // 注册路由
    router.use('/auth', authRoutes);
    router.use('/users', adminAuthMiddleware, userRoutes);
    router.use('/admin-users', adminAuthMiddleware, adminUserRoutes);
    router.use('/content', adminAuthMiddleware, contentRoutes);
    router.use('/version', adminAuthMiddleware, versionRoutes);
    router.use('/dashboard', adminAuthMiddleware, dashboardRoutes);
    router.use('/stats', adminAuthMiddleware, statsRoutes);

    // 处理404
    router.use((req, res) => {
        logger.warn(`404 - 未找到的后台路由: ${req.originalUrl}`);
        res.status(404).json({
            error: 'NotFound',
            message: '请求的后台接口不存在'
        });
    });

    return router;
}

module.exports = initializeAdminModule();